import { reactive } from 'vue'
import * as THREE from 'three'

export function usePhysics() {
  const gravity = 9.8
  const world = reactive({
    objects: []
  })
  
  const addObject = (object) => {
    world.objects.push(object)
  }
  
  const removeObject = (object) => {
    world.objects = world.objects.filter(obj => obj !== object)
  }
  
  const update = (delta) => {
    world.objects.forEach(object => {
      // 应用重力
      if (object.position.y > 0) {
        object.velocity.y -= gravity * delta
      } else {
        object.velocity.y = 0
        object.position.y = 0
      }
      
      // 更新位置
      object.position.x += object.velocity.x * delta
      object.position.y += object.velocity.y * delta
      object.position.z += object.velocity.z * delta
    })
  }
  
  const checkCollision = (obj1, obj2) => {
    const distance = new THREE.Vector3(
      obj1.position.x - obj2.position.x,
      obj1.position.y - obj2.position.y,
      obj1.position.z - obj2.position.z
    ).length()
    
    return distance < (obj1.radius + obj2.radius)
  }
  
  const checkHit = (attack, target) => {
    // 简化版碰撞检测
    const distance = Math.sqrt(
      Math.pow(attack.position.x - target.position.x, 2) +
      Math.pow(attack.position.z - target.position.z, 2)
    )
    
    return distance < attack.range
  }
  
  return {
    world,
    addObject,
    removeObject,
    update,
    checkCollision,
    checkHit
  }
}